package ge.telasi.tasks.ui.comp;

import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultListModel;

/**
 * @author dimitri
 */
public class ListModel<T> extends DefaultListModel {
    protected List<T> data = new ArrayList<T>();

    public T getObjectAt(int index) {
        if (index == -1) {
            return null;
        }
        return data.get(index);
    }

    public List<T> getObjectsAt(int[] indecies) {
        List<T> list = new ArrayList<T>();
        if (indecies != null && indecies.length > 0) {
            for (int index : indecies) {
                T object = getObjectAt(index);
                if (object != null) {
                    list.add(object);
                }
            }
        }
        return list;
    }

    @Override
    public int getSize() {
        return data == null ? 0 : data.size();
    }

    @Override
    public Object getElementAt(int index) {
        return getObjectAt(index);
    }

    public List<T> getData() {
        return data;
    }

    public void setData(List<T> data) {
        this.data = data;
        fireDataChange();
    }

    public void add(T object) {
        if (data == null) {
            data = new ArrayList<T>();
        }
        data.add(object);
        fireDataChange();
    }

    public void addAt(T object, int index) {
        if (data == null) {
            data = new ArrayList<T>();
        }
        data.add(index, object);
        fireDataChange();
    }

    public int replace(T object) {
        int index = getIndexOf(object);
        if (index != -1) {
            data.remove(index);
            data.add(index, object);
            fireDataChange();
        }
        return index;
    }

    public void remove(T object) {
        data.remove(object);
        fireDataChange();
    }

    public int getIndexOf(T object) {
        return data.indexOf(object);
    }

    protected void fireDataChange() {
        int size = data == null ? 0 : data.size();
        fireContentsChanged(this, 0, size);
    }

}
